#coding:utf-8


from backend.serializers import  Lyzd_RunMsgSerializer
from backend.api.getResult import *



#集成CICD的脚本内容
# def makefile(path, script):
#     if os.path.exists(path):
#         if os.path.isdir(path):
#             f = open('makefile_test.txt', 'w+')
#             f.write(script)
#             f.seek(0)
#             read = f.readline()
#             f.close()
#             print(read)
#         else:
#             print('please input the dir name')
#     else:
#         print('the path is not exists')

#cicd脚本内容
def cicdScript(project_id,environment_id,run_ids,case_type_code_id):
    script= "import os, django\n" \
            "import sys\n" \
            "os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"api_automation_test.settings\")\n" \
            "django.setup()\n" \
            "from requests import request\n" \
            "from backend.api.getResult import getResult, Lyzd_RunMsg\n" \
            "from backend.serializers import Lyzd_RunMsgSerializer\n" \
            "def runScript():\n" \
            "\tcontent = {\"progect_id\":"+str(project_id)+",\n" \
                       "\t\t\"environment_id\":"+str(environment_id)+",\n" \
                       "\t\t\"interface_action\":"+str(run_ids)+" ,\n" \
                       "\t\t\"execute\": \'"+str(case_type_code_id)+"\'}\n" \
            "\tmsg = getResult.get(request, content)\n" \
            "\t\"\"\"Query the latest running results\"\"\"\n" \
            "\tmaxid_msg_data = Lyzd_RunMsg.objects.latest()\n" \
            "\tmaxid_msg_data.id\n" \
            "\tmsg_data = Lyzd_RunMsg.objects.filter(id=maxid_msg_data.id)\n" \
            "\tserialize = Lyzd_RunMsgSerializer(msg_data, many=True)\n" \
            "\trunResult = eval(serialize.data[0]['msg'])\n" \
            "\tsum=str(runResult['共执行接口数量'])\n" \
            "\tsuccess=str(runResult['执行成功数量'])\n" \
            "\tfial=str(runResult['执行失败数量'])\n" \
            "\treturnStdout = \"共执行接口数量\"+sum+\"个,执行成功的数量\"+success+\"个,执行失败的数量\"+fial+\"个\"\n" \
            "\treturn returnStdout\n"
    return script

#创建cicd脚本文件，并写入内容
def makefile(pathScriptName,content):
    f = open(pathScriptName, 'w+', encoding="utf-8")
    f.write(content)
    f.close()

# #jenkins文件首行内容
# def jenkinsfirst(scriptName):
#     jenkinsfirst="from backend.script import "+scriptName+"\n"
#     return jenkinsfirst
#
# #jenkins文件尾行内容
# def jenkinsnot(scriptName, jkName):
#     jenkinsnot="elif scriptName == \'"+str(jkName)+"\':\n" \
#             "\t"+str(scriptName)+"=="+str(scriptName)+".runScript()\n"
#     return jenkinsnot
#
# #jenkins文件首行追加内容
# def addjenkinsfirst(pathScriptName,content):
#     with open(pathScriptName, 'r+' ,encoding="utf-8") as f:
#         readcontent = f.read()
#         f.seek(0, 0)
#         f.write(content+readcontent)
#
# #jenkins文件末尾追加内容
# def addjenkinsnot(pathScriptName,content):
#     f = open(pathScriptName, 'a+', encoding="utf-8")
#     f.write(content)
#     f.close()

class createScript(APIView):

    # authentication_classes = (TokenAuthentication,)
    # permission_classes = ()

    def get(self, request):
        """
        获取用例分组
        :return:
        """
        try:
            run_id = request.GET.get("run_ids[]")  # 执行接口列表
            run_ids = run_id.replace("[", '').replace("]", '').replace("/", '')
            run_ids = run_ids.split(",")
            project_id = request.GET.get("project_id")  # 项目
            environment_id = request.GET.get("environment_id")  # 环境id
            case_type_code_id = request.GET.get("case_type_code_id")  # 逻辑执行/常规执行
            script_name=request.GET.get("script_name")
            print(script_name)

            #CICD内容
            script=cicdScript(project_id,environment_id,run_ids,case_type_code_id)
            makefile('./backend/script/'+script_name+'.py', script)

        #jenkins脚本首行追加内容
        # first=jenkinsfirst('ceshi')
        # addjenkinsfirst('jenkins.py',first)
        # nots=jenkinsnot('ceshi','znorder-biz-CD')
        # addjenkinsnot('jenkins.py',nots)


            return JsonResponse(data="", code="999999", msg="脚本创建成功！")
        except:
            return JsonResponse(data="", code="999998", msg="脚本创建失败！")
        # return JsonResponse(data=getResult.get(request,content),code="999999", msg=getResult.get(request,content))
